var makeFlag = 0, clickFlag = 0;
$(function () {
    queryUserList();
});
var flowType = 1;
var flowStepList = [];
var approveNodes = [{id: 1, text: ''}];

function queryUserList() {
    var yellows = doPostSync('/office/user/queryYellow');
    approveNodes = yellows.obj;
}

function addStep() {
    if (makeFlag == 1) {
        showAlert('添加完执行人后不可再添加审核人');
        return false;
    }
    flowStepList.push({});
    var newLength = flowStepList.length;
    var html = `<div style="margin-bottom: 1em" class="stepListItem">
                                    <label id="selectLabel${newLength}" style="display: inline-block;height: 30px;line-height: 30px;float: left">第${newLength}步</label>
                                 <div id="select${newLength}"></div>
                                </div>`;
    $("#stepList").append(html);
    wrapFuzzSelect(newLength);
}

function removeStep() {
    $(".stepListItem").last().remove();
    flowStepList.pop();
    makeFlag = 0
}


function drawFlowStep(flowNodes) {
    if (flowNodes.length > 0) {
        var array = [];
        flowNodes.forEach((item, i) => {
            var checkedArr = item.orgId.split(",");
            if (item.makeFlag == 2) {
                makeFlag = 2;
            }
            array.push(checkedArr);
            var html = ` <div style="margin-bottom: 1em" class="stepListItem">
                                    <label style="display: inline-block;height: 30px;line-height: 30px;float: left">${item.makeFlag == 2 ? '执行人' : '第' + (i + 1) + '步'}</label>
                                 <div id="select${i + 1}"></div>
                            </div>`;
            $("#stepList").append(html);
            flowStepList.push(checkedArr)
            wrapFuzzSelect(i + 1, checkedArr);
        });
    } else {
        $("#stepList").empty();
    }
}

/**提交流程*/
function doSubmit(url, param, jsonFlag) {
    if (clickFlag == 1) {
        showAlert('您已提交了流程,为避免重复提交，请退出后重新进入页面！！！');
        return false;
    }
    var array = [];
    var nodeFlag=true;
    flowStepList.forEach((item, i) => {
        let orgArrayStr = "";
        Object.keys(item).forEach(each => {
            orgArrayStr = orgArrayStr + "," + item[each]
        });
        orgArrayStr = orgArrayStr.substring(1, orgArrayStr.length);
        if (orgArrayStr) {
            let flowNode = {orgId: orgArrayStr};
            array.push(flowNode);
        } else {
            nodeFlag=false
        }
    });
    if (!nodeFlag) {
        showAlert('请补全流程设计');
        return false
    }
    if (array.length == 0) {
        showAlert('请设计流程后提交表单！！！');
        return false;
    }
    if (validateStep(array)) {
        showAlert('流程设计中不能存在重复的审批人！！！');
        return false;
    }
    $.ajax({
        url: url,
        data: jsonFlag ? JSON.stringify(param) : param,
        type: 'post',
        async: true,
        contentType: jsonFlag ? 'application/json' : 'application/x-www-form-urlencoded',
        success: function (res) {
            if (res.code == 200) {
                clickFlag = 1;
                res.obj.flowNodes = array;
                saveFlowStep(res.obj)
            }
        }
    });
}

/***保存流程步骤*/
function saveFlowStep(param) {
    param.flowType = flowType;
    param.userId = getUserId();
    if (makeFlag == 1) {
        param.flowNodes[param.flowNodes.length - 1].makeFlag = 2;
    }
    $.ajax({
        url: '/office/flowStepTemplate/addFlowStepTemplate',
        data: JSON.stringify(param),
        type: 'post',
        async: true,
        contentType: 'application/json',
        success: function (res) {
            if (res.code == 200) {
                closeDialog();
                showMsg(res.msg);
            } else {
                showAlert(res.msg);
            }
        },
    });
}

function wrapFuzzSelect(param, checked) {
    var b = {
        isChecked: true,//是否可以多选
        isSearch: true,//是否可以搜索
        isDelete: false,//是否可以删除
        place: 'bottom',//位置 默认bottom，可选top
        // disabled:true,
        placeholder: '请选择',
        // selected:[1,2,3],
        getClickSelect: function (list, listObj, that) {//每次点击回调
            var map = {};
            listObj.forEach(item => [
                map[item.text] = item.id
            ])
            flowStepList[param - 1] = map;
        },
        height: '200',//选择框高度 默认160
        data: approveNodes,
        dataField: {//下拉数据字段
            text: 'text',
            id: 'id'
        }
    }
    var b = $('#select' + param).SelectPlugin(b);
    if (checked) {
        b.setDefault(checked)
    }
}


/*校验流程设计是否合法*/
function validateStep(array) {
    let flag = false;
    let obj = {};
    let strs = "";
    array.forEach(item => {
        strs += item.orgId + ",";
    });
    strs.split(",").forEach(item => {
        if (obj[item] == "1") {
            flag = true;
        } else {
            obj[item] = "1";
        }
    });
    return flag;
}
function drawAdd() {
    var html = `<div id="app">
    <p style="color: red">流程设计</p>
    <div style="margin-bottom: 1em" id="designButtonList">
        <button id="addClick" onclick="addStep()">添加审核人</button>       
        <button onclick="removeStep()">删除后一步</button>
    </div>
    <div style="clear: both;"></div>
    <div id="stepList"></div>
</div>
<div class="layui-layer-btn layui-layer-btn-" style="    display: inherit;
    margin: 0 auto;
    width: 200px;">
    <a class="layui-layer-btn0" id="save" onclick="submitForm()">保存</a>
</div>`
    $(html).appendTo($("body"))
}

function drawConstance() {
    var html = `<div id="app">
    <p style="color: red">审批步骤</p>
    <div style="clear: both;"></div>
    <div id="stepList"></div>
</div>
<div class="layui-layer-btn layui-layer-btn-" style="    display: inherit;
    margin: 0 auto;
    width: 200px;">
    <a class="layui-layer-btn0" id="save" onclick="submitForm()">保存</a>
</div>`
    $(html).appendTo($("body"))
}


function addExecute() {
    if (makeFlag == 0) {
        flowStepList.push({});
        var newLength = flowStepList.length;
        var html = `<div style="margin-bottom: 1em" class="stepListItem">
                                    <label  style="display: inline-block;height: 30px;line-height: 30px;float: left">执行人</label>
                                 <div id="select${newLength}"></div>
                                </div>`;
        $("#stepList").append(html);
        wrapFuzzSelect(newLength);
        makeFlag = 1;
    } else {
        showAlert('执行人只能添加一次！！！');
        return false;
    }
}

function drawApprove(instanceId) {
    var approveHtml = `<div title="流程进度" id="process">
                        <input type="file" value="请选择文件" hidden/>   
                            <table id="demo" lay-filter="test"></table>
                    </div>`;
    $(approveHtml).appendTo($("form"));
    //渲染审批列表
    layui.use('table', function () {
        var table = layui.table;
        //第一个实例
        table.render({
            elem: '#demo'
            , url: '/office/flowStepInstance/queryInstanceAndProcess?instanceId=' + instanceId //数据接口
            , method: 'post'
            , cols: [[ //表头
                {field: 'stepId', title: '步骤', width: 80, sort: false}
                , {field: 'orgname', title: '组织', width: 200}
                , {field: 'nickName', title: '姓名', width: 100, sort: false}
                , {
                    field: 'status', title: '状态', width: 80, templet: function (row) {
                        return formatterStatus(row.status, row)
                    }
                },
                {
                    field: 'instanceId', title: '操作', width: 150, templet: function (row) {
                        return formatterActon(row)
                    }
                },
                {
                    field: 'updateTime', title: '审批时间', width: 200, templet: function (row) {
                        return dateFormatter(row.updateTime);
                    }
                },
                {field: 'comment', title: '备注', width: 300, sort: false}
            ]],
            parseData: function (res) {
                return {
                    "code": 0,
                    "msg": "",
                    "data": res.obj.flowStepApprove.process
                }
            }
        });
        //渲染退回信息
        $.post("/office/flowStepApprove/getProofList", {instanceId: instanceId}, function (res) {
            var html = "";
            res.obj.forEach(item => {
                item.proof = item.proof ? item.proof : '待发起人处理';
                item.proofAnnex = item.proofAnnex ? `<a target="_blank" href="${item.proofAnnex}?token=${Cookies.get('token')}" style="color: #5094d5">点击查看附件</a>` : '';
                html += `<tr>
            <td>退回人</td>
            <td><span>${item.userName}</span></td>
            <td>处理结果</td>
            <td colspan="4"><div style="width: 100%; height:5em;" class="layui-input" name="department">
                ${item.proof}&nbsp;&nbsp;&nbsp;&nbsp;${item.proofAnnex}
                </div></td>
            </tr>`
            });
            $(html).appendTo($("form table:eq(0)"));
        })
    });
}

/**渲染审核列表状态*/
function formatterStatus(value, row) {
    switch (value) {
        case 1:
            return row.makeFlag == 2 ? '已执行' : '同意';
        case 2:
            return row.makeFlag == 2 ? '待执行' : '待审核';
        case 0:
            return '不同意';
        case 3 :
            return row.makeFlag == 2 ? '待执行' : '待审核';
        case -1:
            return '待审核'
    }
    return '未知参数'
}

var templateId, userId;

function formatterActon(row) {
    if (row.person == getUserId()) {
        if (row.status == 2) {
            if (row.makeFlag == 2) {
                return `<a class="layui-btn layui-btn-sm" onclick="openApprove('${row.templateId}','${row.person}','${row.makeFlag}')">执行</a>`
            } else {
                return `<a class="layui-btn layui-btn-xs" onclick="openApprove('${row.templateId}','${row.person}','${row.makeFlag}','')">审核</a>`
            }
        } else if (row.status == 1 || parseInt(row.status) === 0) {
            return `<a class="layui-btn layui-btn-sm" onclick="uploadAnnex('${row.instanceId}','${row.person}')">上传附件</a>`
        } else if (row.status == -1) {
            return ''
        }
    }
    return "";
}

var cbAnnexFile;

function uploadAnnex(instanceId) {
    var input = document.createElement("input");
    input.type = "file";
    input.click(); //代码执行到这里，本地文件选择框便会打开！
    input.onchange = function () {
        cbAnnexFile = input.files[0];
        layer.confirm('是否确定上传' + cbAnnexFile.name + '?', function (i) {
            var formData = new FormData();
            formData.append("file", cbAnnexFile); //第一个参数是后台读取的请求key值
            let result = uploadFile(formData);
            if (result.code == 200) {
                closeDialog();
                showMsg(result.msg);
                $.post('/office/flowStepInstance/updateFlowInstance', {
                    instanceId: instanceId,
                    comment: result.obj.url,
                    person: getUserId()
                }, function (res) {
                    if (res.code == 200) {
                        showAlert('附件上传成功，再次刷新后查看', 1);
                    }
                })
            }
        })
    };
}

function openApprove(templateId, userId, makeFlag) {
    this.templateId = templateId;
    this.userId = userId;
    var content;
    if (makeFlag == 2) {
        content = `<form id="approveForm">
    <table cellspacing="8px" id="table">
        <tr hidden>
            <td>审批意见:</td>
            <td>
                <label>同意</label><input name="status" type="radio" checked="checked" value="1"
                                        style="display: inline-block;"/>
            </td>
        </tr>
        <tr>
            <td valign="top">备注:</td>
            <td><textarea id="remarks" name="comment" rows="5" cols="40"></textarea></td>

        </tr>
        <tr id="dispatch">
        </tr>
    </table>
    <div class="layui-layer-btn layui-layer-btn-">
        <a class="layui-layer-btn0" onclick="submitApprove()">已执行</a>
    </div>
</form>`
    } else {
        content = `<form id="approveForm">
                    <table cellspacing="8px" id="table">
        <tr>
            <td>审批意见:</td>
            <td style="  display: flex;justify-content: space-around;">
                <div><input name="status" type="radio" value="1"/><label>同意</label></div>
                <div><input name="status" type="radio" value="0"/><label>不同意</label></div>
                ${this.showReturnButton ? '<div><input name="status" type="radio" value="-1"/><label>退回</label></div>' : ''}
            </td>
        </tr>
        <tr>
            <td valign="top">备注:</td>
            <td><textarea id="remarks" name="comment" rows="5" cols="40"></textarea></td>

        </tr>
        <tr id="dispatch">
        </tr>
    </table>
    <div class="layui-layer-btn layui-layer-btn-">
        <a class="layui-layer-btn0" onclick="submitApprove()">保存</a>
        <a class="layui-layer-btn1" class="easyui-linkbutton" onclick="closeDialog()">取消</a>
    </div>
</form>`
    }
    parent.layer.open({
        type: 1,
        title: '流程审批',
        area: screen() < 2 ? ['50%', '60%'] : ['50%', '60%'],
        content: content
    })
}


